//
//  FilmTableVC.m
//  Buiom_7.0
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 triffe. All rights reserved.
//

#import "FilmTableVC.h"
#import "NewsModel.h"
#import "TrailerModel.h"
#import "TopListsModel.h"
#import "WheelPicManager.h"
#import "FirstCell.h"
#import "SecondCell.h"
#import "ThirdCell.h"
#import "FourthCell.h"
#import "NewsDetailVC.h"
#import "TrailerDetailVC.h"
#import "TopListDetailVC.h"


@interface FilmTableVC ()<MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) NSMutableArray *wheelArray;
@property (nonatomic, strong) NSString *urlStr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@end

@implementation FilmTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = NO;
    self.page = 1;
    WheelPicManager *manager = [WheelPicManager shareManager];
    [manager ConnectionWithBlock:^(NSArray *array) {
        self.wheelArray = [NSMutableArray arrayWithArray:array];
        [self.tableView reloadData];
    }];
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing) dateKey:@"MJ"];
    // [self.tableView headerBeginRefreshing];
    // 上拉加载更多
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"刷新中。。。";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"加载中。。。";
    // 添加动画加载等待
    self.indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.tableView.center;
    CGPoint point = _indicatorView.center;
    point.y = self.tableView.center.y - 200;
    _indicatorView.center = point;
    _indicatorView.delegate = self;
    [self.tableView addSubview:_indicatorView];
    [_indicatorView startAnimating];
    

    [self.tableView registerNib:[UINib nibWithNibName:@"ThirdCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"FourthCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"toplist"];
    
}




#pragma mark -- 添加加载圆圈动画的方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    if (index == 0) {
        return [UIColor redColor];
    }if (index == 1) {
        return [UIColor magentaColor];
    }if (index == 2) {
        return [UIColor orangeColor];
    }if (index == 3) {
        return [UIColor purpleColor];
    }
    return [UIColor yellowColor];
}


#pragma mark -- 加载和刷新
- (void)headerRefreshing
{
    if (self.urlStr == nil) {
        self.urlStr = KNewsUrl;
    }
    [self.dataArray removeAllObjects];
    [self urlConnectionWithURLString:self.urlStr];
    [self.tableView headerEndRefreshing];
}

//上拉加载
- (void)footerRereshing
{
    //这个一般是提取缓存的数据
    if (self.urlStr == nil) {
        // [self.tableView footerEndRefreshing];
    } else if ([self.urlStr isEqualToString:KNewsUrl]) {
        self.page++;
        NSString *oldStr = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=%ld",(long)self.page];
        NSURL *url = [NSURL URLWithString:oldStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        [request setHTTPMethod:@"GET"];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                NSArray *array = dictionary[@"newsList"];
                for (NSDictionary *dic in array) {
                    NewsModel *model = [[NewsModel alloc] init
                                        ];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
            [self.tableView reloadData];
            //2,结束刷新
            [self.tableView footerEndRefreshing];
        }];
        return;

        
    } else if ([self.urlStr isEqualToString:KTopListURL]) {
        self.page++;
        NSString *oldStr = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=%ld",(long)self.page];
        NSURL *url = [NSURL URLWithString:oldStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        [request setHTTPMethod:@"GET"];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *array = dictionary[@"topLists"];
            for (NSDictionary *dic in array) {
                TopListsModel *model = [[TopListsModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
        }];

        return;
    }
    
    [self.tableView footerEndRefreshing];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count + 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataArray.count > 0) {
        if ([self.urlStr isEqualToString:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=1"]) {
            if (indexPath.row == 0) {
                NSString *identifier = @"FirstCell";
                FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    cell = [[FirstCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                NSDictionary *dic = self.wheelArray[0];
                [cell.picView sd_setImageWithURL:[NSURL URLWithString:dic[@"imageUrl"]] placeholderImage:nil];
                cell.titLable.text = dic[@"title"];
                return cell;
            } else {
                NewsModel *model = self.dataArray[indexPath.row - 1];
                ThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

                [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:nil];
                cell.titLable.text = model.title;
                cell.desLable.text = model.title2;
                return cell;
            }
        }
    
    else if ([self.urlStr isEqualToString:KTrailerUrl]) {
            if (indexPath.row == 0) {
                NSString *identifier = @"FirstCell";
                FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    cell = [[FirstCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                NSDictionary *dic = self.wheelArray[1];
                [cell.picView sd_setImageWithURL:[NSURL URLWithString:dic[@"imageUrl"]] placeholderImage:nil];
                cell.titLable.text = dic[@"title"];
                return cell;
            } else {
                TrailerModel *model = self.dataArray[indexPath.row - 1];
//                ThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
                
                NSString *identifier = @"SY";
                SecondCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    cell = [[SecondCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }

                [cell.leftPicView sd_setImageWithURL:[NSURL URLWithString:model.coverImg] placeholderImage:nil];
                // cell.midPicView.image = [UIImage imageNamed:@"play"];
                cell.titLable.text = model.movieName;
                cell.replyLable.text = model.summary;
                return cell;
            }
        }
            else if ([self.urlStr isEqualToString:@"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=1"]) {
            if (indexPath.row == 0) {
                NSString *identifier = @"FirstCell";
                FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    cell = [[FirstCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                NSDictionary *dic = self.wheelArray[2];
                [cell.picView sd_setImageWithURL:[NSURL URLWithString:dic[@"imageUrl"]] placeholderImage:nil];
                cell.titLable.text = dic[@"title"];
                return cell;
            } else {
                TopListsModel *model = self.dataArray[indexPath.row - 1];
                FourthCell *cell = [tableView dequeueReusableCellWithIdentifier:@"toplist" forIndexPath:indexPath];
                cell.titLable.text = model.topListNameCn;
                cell.desLable.text = model.summary;
                return cell;
            }
            
        }
    
        
    }


    NSString *identifier = @"YS";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    
    
    return cell;
}

#pragma mark -- 返回高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 250;
    } else if ([self.urlStr isEqualToString:KTopListURL]) {
        return 80;
    } else if ([self.urlStr isEqualToString:KTrailerUrl]) {
        return 150;
    }
    
    return 160;
}

#pragma mark -- 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.urlStr isEqualToString:KNewsUrl]) {
        if (indexPath.row == 0) {
            NSDictionary *dictionary = self.wheelArray[0];
            NewsDetailVC *newsDVC = [[NewsDetailVC alloc] init];
            newsDVC.newsID = dictionary[@"newsID"];
            newsDVC.NewsTitle = dictionary[@"title"];
            newsDVC.imageURL = dictionary[@"imageUrl"];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:newsDVC];
            // 模态动画
            navC.modalPresentationStyle = UIModalPresentationFullScreen;
            navC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self presentViewController:navC animated:YES completion:nil];
            return;
        }
        NewsModel *model = self.dataArray[indexPath.row - 1];
        NewsDetailVC *newsDVC = [[NewsDetailVC alloc] init];
        newsDVC.newsID = model.ID;
        newsDVC.NewsTitle = model.title;
        newsDVC.imageURL = model.image;
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:newsDVC];
        // 模态动画
        navC.modalPresentationStyle = UIModalPresentationFullScreen;
        navC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:navC animated:YES completion:nil];
        
    } else if ([self.urlStr isEqualToString:KTrailerUrl]) {
        if (indexPath.row == 0) {
            NSDictionary *dictionary = self.wheelArray[1];
            TrailerDetailVC *trailerVC = [[TrailerDetailVC alloc] init];
            trailerVC.UrlStr = dictionary[@"mp4Url"];
            trailerVC.trailStr = dictionary[@"title"];
            trailerVC.imageURL = dictionary[@"imageUrl"];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:trailerVC];
            [self presentViewController:navC animated:YES completion:nil];
            return;
        }

        TrailerModel *model = self.dataArray[indexPath.row - 1];
        TrailerDetailVC *trailerVC = [[TrailerDetailVC alloc] init];
        trailerVC.UrlStr = model.url;
        trailerVC.trailStr = model.movieName;
        trailerVC.imageURL = model.coverImg;
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:trailerVC];
        [self presentViewController:navC animated:YES completion:nil];
        
    } else if ([self.urlStr isEqualToString:KTopListURL]){
        if (indexPath.row == 0) {
            NSDictionary *dictionary = self.wheelArray[2];
            TopListDetailVC *topVC = [[TopListDetailVC alloc] init];
            topVC.topID = dictionary[@"id"];
            topVC.titleStr = dictionary[@"title"];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:topVC];
            // 模态动画
            navC.modalPresentationStyle = UIModalPresentationFullScreen;
            navC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

            [self presentViewController:navC animated:YES completion:nil];
            return;
        }

        TopListsModel *model = self.dataArray[indexPath.row - 1];
        TopListDetailVC *topVC = [[TopListDetailVC alloc] init];
        topVC.topID = model.ID;
        topVC.titleStr = model.topListNameCn;
        topVC.summaryStr = model.summary;
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:topVC];
        navC.modalPresentationStyle = UIModalPresentationFullScreen;
        navC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentViewController:navC animated:YES completion:nil];
    }

}



#pragma mark -- 传进网址,解析数据
- (void)urlConnectionWithURLString:(NSString *)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    self.urlStr = urlString;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (data == nil) {
            return;
        }
        if ([urlString isEqualToString:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=1"]) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *array = dictionary[@"newsList"];
            for (NSDictionary *dic in array) {
                NewsModel *model = [[NewsModel alloc] init
                                    ];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            
            
        } else if ([urlString isEqualToString:@"http://api.m.mtime.cn/PageSubArea/TrailerList.api"]) {
            NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *array = diction[@"trailers"];
            for (NSDictionary *dic in array) {
                TrailerModel *model = [[TrailerModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            
        } else if ([urlString isEqualToString:@"http://api.m.mtime.cn/TopList/TopListOfAll.api?pageIndex=1"]) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *array = dictionary[@"topLists"];
            for (NSDictionary *dic in array) {
                TopListsModel *model = [[TopListsModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
        }
        
        [self.tableView reloadData];
        [_indicatorView stopAnimating];
        
        
    }];
}
// 懒加载dataArray
- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
